#!/usr/bin/env python3
"""
验证项目设置的脚本
检查导入、配置和基本功能是否正常
"""

import sys
import traceback
from pathlib import Path

def test_imports():
    """测试导入功能"""
    print("🔍 测试导入功能...")
    
    try:
        from app.base.logger import setup_logger
        print("✅ app.base.logger 导入成功")
    except ImportError as e:
        print(f"❌ app.base.logger 导入失败: {e}")
        return False
    
    try:
        from app.utils.config_manager import config
        print("✅ app.utils.config_manager 导入成功")
    except ImportError as e:
        print(f"❌ app.utils.config_manager 导入失败: {e}")
        return False
    
    try:
        from app.service.milvus_service import MilvusService, MilvusFields
        print("✅ app.service.milvus_service 导入成功")
    except ImportError as e:
        print(f"❌ app.service.milvus_service 导入失败: {e}")
        return False
    
    try:
        from app.service.knowledge_graph_service import knowledge_graph_service
        print("✅ app.service.knowledge_graph_service 导入成功")
    except ImportError as e:
        print(f"❌ app.service.knowledge_graph_service 导入失败: {e}")
        return False
    
    return True

def test_config():
    """测试配置功能"""
    print("\n🔍 测试配置功能...")
    
    try:
        from app.utils.config_manager import config
        
        # 检查配置文件是否存在
        config_file = Path("app/config.properties")
        if config_file.exists():
            print("✅ 配置文件存在")
        else:
            print("⚠️  配置文件不存在，请运行 python setup_dev.py")
        
        # 测试配置读取
        milvus_config = config.milvus_config
        nebula_config = config.nebula_config
        embedding_config = config.embedding_config
        
        print("✅ 配置读取成功")
        print(f"   Milvus URI: {milvus_config.get('uri', 'Not configured')}")
        print(f"   Nebula IP: {nebula_config.get('ip', 'Not configured')}")
        print(f"   Embedding Model: {embedding_config.get('model_name', 'Not configured')}")
        
        return True
        
    except Exception as e:
        print(f"❌ 配置测试失败: {e}")
        return False

def test_logger():
    """测试日志功能"""
    print("\n🔍 测试日志功能...")
    
    try:
        from app.base.logger import setup_logger
        
        logger = setup_logger("test_logger")
        logger.info("这是一条测试日志")
        
        print("✅ 日志功能正常")
        return True
        
    except Exception as e:
        print(f"❌ 日志测试失败: {e}")
        return False

def test_milvus_fields():
    """测试Milvus字段常量"""
    print("\n🔍 测试Milvus字段常量...")
    
    try:
        from app.service.milvus_service import MilvusFields
        
        print("✅ Milvus字段常量:")
        print(f"   ID_FIELD: {MilvusFields.ID_FIELD}")
        print(f"   TEXT_DENSE: {MilvusFields.TEXT_DENSE}")
        print(f"   TEXT_SPARSE: {MilvusFields.TEXT_SPARSE}")
        print(f"   CONTENT: {MilvusFields.CONTENT}")
        
        return True
        
    except Exception as e:
        print(f"❌ Milvus字段测试失败: {e}")
        return False

def test_project_structure():
    """测试项目结构"""
    print("\n🔍 测试项目结构...")
    
    required_files = [
        "main.py",
        "run.py", 
        "setup_dev.py",
        "pyproject.toml",
        "requirements.txt",
        "app/__init__.py",
        "app/base/logger.py",
        "app/utils/config_manager.py",
        "app/service/milvus_service.py",
        "app/service/knowledge_graph_service.py"
    ]
    
    missing_files = []
    for file_path in required_files:
        if not Path(file_path).exists():
            missing_files.append(file_path)
    
    if missing_files:
        print(f"❌ 缺少文件: {', '.join(missing_files)}")
        return False
    else:
        print("✅ 项目结构完整")
        return True

def main():
    """主函数"""
    print("🚀 开始验证Maling Query后端项目设置")
    print("=" * 50)
    
    # 检查是否在backend目录
    if not Path("app").exists() or not Path("main.py").exists():
        print("❌ 请在backend目录下运行此脚本")
        sys.exit(1)
    
    tests = [
        ("项目结构", test_project_structure),
        ("导入功能", test_imports),
        ("配置功能", test_config),
        ("日志功能", test_logger),
        ("Milvus字段", test_milvus_fields),
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        try:
            if test_func():
                passed += 1
            else:
                print(f"⚠️  {test_name} 测试未完全通过")
        except Exception as e:
            print(f"❌ {test_name} 测试异常: {e}")
            traceback.print_exc()
    
    print("\n" + "=" * 50)
    print(f"📊 测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("🎉 所有测试通过！项目设置正确")
        print("\n📋 后续步骤:")
        print("1. 编辑 app/config.properties 配置文件")
        print("2. 启动服务: python run.py")
        print("3. 运行测试: python run.py test")
    else:
        print("⚠️  部分测试未通过，请检查项目设置")
        
        if not Path("app/config.properties").exists():
            print("\n💡 提示: 运行 python setup_dev.py 来自动设置开发环境")

if __name__ == "__main__":
    main()
